<template>
  <div id="RecordBackPage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">评估筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">评估时间</span>
          <el-date-picker
            class="item-input"
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">任务名称</span>
          <el-input
            class="item-input"
            v-model="queryObj.name"
            placeholder="输入任务名称"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">评估媒资</span>
          <el-input
            class="item-input"
            style="width: 15rem"
            v-model="queryObj.resourceName"
            placeholder="输入评估媒资名称"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">评估专家</span>
          <el-select
            class="item-input"
            style="width: 15rem"
            v-model="queryObj.expertIds"
            placeholder="选择评估专家"
            multiple
            clearable
            collapse-tags
            collapse-tags-tooltip
            @change="searchHandle"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.userName"
              :value="user.id"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">综合得分区间</span>
          <el-input
            class="item-input"
            style="width: 10rem"
            v-model="queryObj.minScore"
            placeholder="输入分值"
            clearable
          />
          <span style="padding: 0 5px">至</span>
          <el-input
            class="item-input"
            style="width: 10rem"
            v-model="queryObj.maxScore"
            placeholder="输入分值"
            clearable
          />
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">评估详情</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="name" label="任务名称" />
          <el-table-column label="评估时间">
            <template #default="scope">
              <div>
                {{ formatTime(scope.row.startTime, "YYYY-MM-DD") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="综合得分">
            <template #default="scope">{{
              scope.row.totalAbsoluteScore
            }}</template>
          </el-table-column>
          <el-table-column label="参与专家">
            <template #default="scope">
              <div>
                {{
                  scope.row.expertList
                    .map((item: ExpertType) => item.userName)
                    .join(",")
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="评估媒资">
            <template #default="scope">
              <div>{{ scope.row.resourceName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="任务描述">
            <template #default="scope">
              <div>{{ scope.row.desc }}</div>
            </template>
          </el-table-column>
          <el-table-column label="评估模板">
            <template #default="scope">
              <div
                class="table-btn"
                @click="showTemplateHandle(scope.row.templateId)"
              >
                {{ scope.row.templateName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right" width="100">
            <template #default="scope">
              <div class="table-btn" @click="showResultHandle(scope.row.id)">
                查看
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.currentPage"
        :total="pagination.totalCount"
        :page-size="pagination.numPerPage"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 查看模板弹框 -->
    <el-dialog
      class="template-dialog self-dialog"
      v-model="dialogTemplateVisible"
      title="查看模板"
      width="80%"
      :before-close="handleTemplateClose"
    >
      <div class="template-form">
        <div class="template-form-item">
          <span class="label">模板名称</span>
          <span class="value">{{ templateForm.name }}</span>
        </div>
        <div class="template-form-item">
          <span class="label">模板说明</span>
          <span class="value">{{ templateForm.note }}</span>
        </div>
      </div>
      <div class="quota-section">
        <el-table :data="quotaList" stripe class="self-stripe-table">
          <el-table-column label="序号" width="60" align="center">
            <template #default="{ $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column label="一级指标" width="200">
            <template #default="{ row }">
              <div>{{ row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="二级指标" min-width="300">
            <template #default="{ row }">
              <div style="white-space: pre-wrap; line-height: 1.8">
                {{ row.evaluationCriteria }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分值" width="150">
            <template #default="{ row }">
              <div>{{ row.evaluationScore }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 查看结果弹框 -->
    <el-dialog
      class="result-dialog self-dialog"
      v-model="dialogResultVisible"
      title="评分详情"
      width="90%"
      :before-close="handleResultClose"
    >
      <div v-if="currentResultTask" class="result-content">
        <!-- 任务基本信息 -->
        <div class="task-info">
          <div class="info-item">
            <span class="label">任务名称：</span>
            <span class="value">{{ currentResultTask.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">评估媒资：</span>
            <span class="value">{{ currentResultTask.resourceName }}</span>
          </div>
          <div class="info-item">
            <span class="label">评估时间：</span>
            <span class="value">{{
              currentResultTask.startTime
                ? formatTime(currentResultTask.startTime, "YYYY-MM-DD")
                : ""
            }}</span>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
          <!-- 左侧：资源预览 -->
          <div class="left-section">
            <div class="preview-wrapper">
              <XGPlayer :url="currentResourcePreviewUrl" />
            </div>
          </div>

          <!-- 右侧：结果表格 -->
          <div class="right-section">
            <!-- 专家选择标签 -->
            <div class="tabs-wrapper">
              <div
                class="tab-item"
                :class="resultCurrentTab === '' ? 'active' : ''"
                @click="getResultEvaluateTaskResult()"
              >
                总体评价
              </div>
              <div
                class="tab-item"
                :class="resultCurrentTab === expert.id ? 'active' : ''"
                v-for="expert in currentResultTask.expertList"
                :key="expert.id"
                @click="getResultEvaluateTaskResult(expert.id)"
              >
                {{ expert.userName }}
              </div>
            </div>

            <!-- 结果表格 -->
            <div class="result-table">
              <!-- 总体评价表格 -->
              <el-table
                v-if="resultCurrentTab === ''"
                :data="resultTableQuotaList"
                stripe
                fit
                class="self-stripe-table"
                height="100%"
              >
                <el-table-column type="index" label="序号" width="60">
                  <template #default="scope">
                    <div>{{ scope.$index + 1 }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="指标">
                  <template #default="scope">
                    <div>{{ scope.row.name }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="平均分">
                  <template #default="scope">
                    <div class="average-score">
                      {{
                        getScore(
                          resultCurrentTabDataMap[scope.row.id]?.averageScore
                        )
                      }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="中位数">
                  <template #default="scope">
                    <div class="average-score">
                      {{
                        getScore(
                          resultCurrentTabDataMap[scope.row.id]?.medianScore
                        )
                      }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="标准差">
                  <template #default="scope">
                    <div class="average-score">
                      {{
                        getScore(
                          resultCurrentTabDataMap[scope.row.id]
                            ?.standardDeviationScore
                        )
                      }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="
                    '权重得分： ' +
                    (resultCurrentTabDataMap['total']?.absoluteScore > 0
                      ? getScore(
                          resultCurrentTabDataMap['total']?.absoluteScore
                        )
                      : '--')
                  "
                >
                  <template #default="scope">
                    <div class="total-score">
                      {{
                        getScore(
                          resultCurrentTabDataMap[scope.row.id]?.absoluteScore
                        )
                      }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 专家个人评价表格 -->
              <el-table
                v-else
                :data="resultTableQuotaList"
                stripe
                fit
                class="self-stripe-table"
                height="100%"
              >
                <el-table-column type="index" label="序号" width="60">
                  <template #default="scope">
                    <div>{{ scope.$index + 1 }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="指标">
                  <template #default="scope">
                    <div>{{ scope.row.name }}</div>
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(segment, index) in resultTimeSegments"
                  :key="segment.label"
                  :label="segment.label"
                  align="center"
                >
                  <template #default="scope">
                    <div
                      class="score-cell"
                      v-if="resultScoreData[scope.row.id]"
                    >
                      {{
                        getScore(resultScoreData[scope.row.id][index]) || "--"
                      }}
                    </div>
                    <div v-else class="score-cell">--</div>
                  </template>
                </el-table-column>
                <el-table-column label="平均分">
                  <template #default="scope">
                    <div class="average-score">
                      {{
                        getScore(
                          resultCurrentTabDataMap[scope.row.id]?.averageScore
                        )
                      }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="
                    '权重得分： ' +
                    getScore(resultCurrentTabDataMap['total']?.absoluteScore)
                  "
                >
                  <template #default="scope">
                    <div class="total-score">
                      {{
                        getScore(
                          resultCurrentTabDataMap[scope.row.id]?.absoluteScore
                        )
                      }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { formatTime, getScore } from "@/assets/js/utils";
import { ListResponseType, PaginationType } from "@/api/globalType";
import {
  getevaluateTaskListAPI,
  getevaluateTaskDetailAPI,
  EvaluateTaskType,
  ExpertType,
  GetevaluateTaskListQueryType,
} from "@/api/service/evaluateTask";

import {
  getEvaluateTaskResultAPI,
  EvaluateTaskResultType,
} from "@/api/service/evaluateTaskResult";

import {
  getTemplateDetailAPI,
  GetTemplateDetailResponseType,
  AddOrUpdateTemplateQueryType,
} from "@/api/service/template";

import { getUserListAPI, UserType } from "@/api/service/user";
import { QuotaType, getQuotaListAPI } from "@/api/service/quota";
import {
  getLiveResourceDetailAPI,
  LiveResourceType,
} from "@/api/service/liveResource";
import {
  getVodResourceDetailAPI,
  VodResourceType,
} from "@/api/service/vodResource";
import {
  getTerminalResourceDetailAPI,
  TerminalResourceType,
} from "@/api/service/terminalResource";
import XGPlayer from "@/components/Player/xgplayer.vue";
import { useRoute } from "vue-router";

const route = useRoute();
const addBtn = route.query.addBtn as string;
const isShowAddBtn = ref(true);
if (addBtn === "true") {
  isShowAddBtn.value = true;
}

const instance = getCurrentInstance();
// 访问全局数据
const globalData = instance?.appContext.config.globalProperties.$globalData;

// 查询条件
const queryObj = ref<GetevaluateTaskListQueryType>({
  name: "",
  resourceName: "",
  expertIds: [],
  startTime: "",
  endTime: "",
  minScore: null,
  maxScore: null,
});

// 日期范围
const timeRange = ref<[string, string] | null>(null);

// 用户列表
const userList = ref<UserType[]>([]);

// 分页
const pagination = ref<PaginationType>({
  currentPage: 1,
  numPerPage: 50,
  totalCount: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<EvaluateTaskType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);
// 获取用户列表
const getUserList = () => {
  getUserListAPI({
    currentPage: 1,
    numPerPage: 1000, // 获取所有用户
  })
    .then((_data: any) => {
      const data = _data as any;
      userList.value = data.list || [];
    })
    .catch(() => {
      ElMessage.error("获取用户列表失败");
    });
};

// 获取任务列表
const getTaskList = () => {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  // 处理时间范围
  if (timeRange.value && timeRange.value.length === 2) {
    queryObj.value.startTime = timeRange.value[0];
    queryObj.value.endTime = timeRange.value[1];
  } else {
    queryObj.value.startTime = "";
    queryObj.value.endTime = "";
  }

  getevaluateTaskListAPI({
    name: queryObj.value.name || undefined,
    resourceName: queryObj.value.resourceName || undefined,
    expertIds:
      queryObj.value.expertIds && queryObj.value.expertIds.length > 0
        ? queryObj.value.expertIds
        : undefined,
    startTime: queryObj.value.startTime || undefined,
    endTime: queryObj.value.endTime || undefined,
    execStatus: 3,
    currentPage: pagination.value.currentPage,
    numPerPage: pagination.value.numPerPage,
    minScore: Number(queryObj.value.minScore) || null,
    maxScore: Number(queryObj.value.maxScore) || null,
  })
    .then((_data: any) => {
      const data = _data as ListResponseType<EvaluateTaskType>;
      tableData.value = data.list;
      pagination.value.totalCount = data.totalCount;
      pagination.value.totalPages = Math.ceil(
        data.totalCount / pagination.value.numPerPage
      );
    })
    .finally(() => {
      listApiLoading.value = false;
    });
};

// 初始化数据
getUserList();
getTaskList();

// 筛选
function searchHandle() {
  pagination.value.currentPage = 1;
  getTaskList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.numPerPage = size;
  pagination.value.currentPage = 1;
  getTaskList();
}
// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.currentPage = currentPage;
  getTaskList();
}

// 查看模板
const dialogTemplateVisible = ref(false);
const detailApiLoading = ref(false);
const templateForm = ref<AddOrUpdateTemplateQueryType>({
  id: null,
  name: "",
  note: "",
});
// 指标列表
const quotaList = ref<QuotaType[]>([]);

function showTemplateHandle(templateId: string) {
  // 防止并发调用
  if (detailApiLoading.value) return;

  detailApiLoading.value = true;

  getTemplateDetailAPI({ templateId })
    .then((_data: any) => {
      const data = _data as GetTemplateDetailResponseType;
      templateForm.value = {
        id: data.id,
        name: data.name,
        note: data.note || "",
      };
      const quotaData = data.quotaList || [];

      quotaData.forEach((quota) => {
        if (quota.evaluationCriteria) {
          quota.evaluationCriteria = formatEvaluationCriteria(
            quota.evaluationCriteria
          );
        }
      });
      quotaList.value = quotaData;
      dialogTemplateVisible.value = true;
    })
    .catch(() => {
      ElMessage.error("获取模板详情失败");
    })
    .finally(() => {
      detailApiLoading.value = false;
    });
}

// 处理二级指标输入 - 自动添加实心圆点
function formatEvaluationCriteria(text: string): string {
  if (!text || !text.trim()) return text;

  const lines = text
    .split("\n")
    .map((line) => line.trim())
    .filter((line) => line.length > 0)
    .map((line) => {
      // 如果行已经有实心圆点，就不重复添加
      if (line.startsWith("● ")) {
        return line;
      }
      // 移除可能存在的其他项目符号（如"1、"、"•"、"-"等）
      const cleanLine = line.replace(/^[1-9]+[、.)]\s*|^[•\-*]\s*|^●\s*/, "");
      return cleanLine ? `● ${cleanLine}` : "";
    })
    .filter((line) => line.length > 0);

  return lines.join("\n");
}

// 关闭弹框
function handleTemplateClose() {
  dialogTemplateVisible.value = false;
  templateForm.value = {
    id: null,
    name: "",
    note: "",
  };
  quotaList.value = [];
}

// 查看结果弹框相关数据
const dialogResultVisible = ref(false);
const currentResultTask = ref<EvaluateTaskType | null>(null);
const currentResourcePreviewUrl = ref<string>("");
const resultCurrentTab = ref<string>("");
const resultCurrentTabDataMap = ref<
  Record<
    string,
    {
      averageScore: number;
      absoluteScore: number;
      medianScore: number;
      standardDeviationScore: number;
    }
  >
>({});
const resultTimeSegments = ref<Array<{ label: string; duration: number }>>([]);
const resultScoreData = ref<Record<string, Record<string, number>>>({});
const resultQuotaList = ref<QuotaType[]>([]);
const resultTableQuotaList = ref<any[]>([]);

// 查看结果
function showResultHandle(taskId: string) {
  // 获取任务详情
  getevaluateTaskDetailAPI({ evaluateTaskId: taskId })
    .then((_data: any) => {
      const data = _data as EvaluateTaskType;
      currentResultTask.value = data;
      dialogResultVisible.value = true;

      // 获取资源预览URL
      getResourcePreviewUrl(data.resourceType, data.resourceId);

      // 获取模板指标列表
      getResultQuotaList(data.templateId);

      // 初始化为总体评价
      resultCurrentTab.value = "";
      getResultEvaluateTaskResult();
    })
    .catch(() => {
      ElMessage.error("获取任务详情失败");
    });
}

// 获取资源预览URL
const getResourcePreviewUrl = (resourceType: string, resourceId: string) => {
  if (resourceType === "直播") {
    getLiveResourceDetailAPI({ liveResourceId: resourceId })
      .then((_data: any) => {
        const data = _data as LiveResourceType;
        currentResourcePreviewUrl.value = data?.previewUrl || "";
      })
      .catch(() => {
        currentResourcePreviewUrl.value = "";
      });
  } else if (resourceType === "点播") {
    getVodResourceDetailAPI({ vodResourceId: resourceId })
      .then((_data: any) => {
        const data = _data as VodResourceType;
        currentResourcePreviewUrl.value = data?.previewUrl || "";
      })
      .catch(() => {
        currentResourcePreviewUrl.value = "";
      });
  } else if (resourceType === "终端") {
    getTerminalResourceDetailAPI({ terminalResourceId: resourceId })
      .then((_data: any) => {
        const data = _data as TerminalResourceType;
        currentResourcePreviewUrl.value = data?.previewUrl || "";
      })
      .catch(() => {
        currentResourcePreviewUrl.value = "";
      });
  }
};

// 获取结果页面的指标列表
const getResultQuotaList = (templateId: string) => {
  getQuotaListAPI({
    templateId,
  }).then((_data: any) => {
    const data = _data as QuotaType[];
    resultQuotaList.value = data;
    resultTableQuotaList.value = data;

    // 计算打分分段
    if (currentResultTask.value) {
      calculateResultTimeSegments(
        currentResultTask.value.planDuration,
        currentResultTask.value.segmentTime
      );
      initializeResultScoreData();
    }
  });
};

// 获取评价任务结果
const getResultEvaluateTaskResult = (expertId?: string) => {
  if (!currentResultTask.value) return;

  getEvaluateTaskResultAPI({
    evaluateTaskId: currentResultTask.value.id,
    expertId,
  })
    .then((_data: any) => {
      const data = _data as EvaluateTaskResultType[];
      resultCurrentTab.value = expertId || "";
      if (Array.isArray(data) && data.length > 0) {
        // 创建新的评分数据对象，确保响应式更新
        const newScoreData: Record<
          string,
          {
            averageScore: number;
            absoluteScore: number;
            medianScore: number;
            standardDeviationScore: number;
          }
        > = {};
        data?.forEach((item) => {
          if (item.isTotalScore === true) {
            newScoreData["total"] = {
              averageScore: item.averageScore || 0,
              absoluteScore: item.absoluteScore || 0,
              medianScore: item.medianScore || 0,
              standardDeviationScore: item.standardDeviationScore || 0,
            };
          } else {
            newScoreData[item.quotaId] = {
              averageScore: item.averageScore || 0,
              absoluteScore: item.absoluteScore || 0,
              medianScore: item.medianScore || 0,
              standardDeviationScore: item.standardDeviationScore || 0,
            };
          }
        });
        // 替换整个对象以触发Vue响应式更新
        resultCurrentTabDataMap.value = newScoreData;

        // 解析已有的评价结果并回显到界面
        parseAndFillResultExistingResults(data);
      } else {
        resultCurrentTabDataMap.value = {};
        resultScoreData.value = {};
      }
    })
    .catch((err) => {
      ElMessage.error("获取评价任务结果失败");
    });
};

// 初始化结果页面评分数据结构
const initializeResultScoreData = () => {
  resultQuotaList.value.forEach((quota) => {
    if (quota.id) {
      const quotaId = quota.id;
      // 如果该指标还没有数据，则初始化
      if (!resultScoreData.value[quotaId]) {
        resultScoreData.value[quotaId] = {};
      }

      // 为每个时间段初始化分数（如果还没有分数的话）
      resultTimeSegments.value.forEach((segment, index) => {
        if (resultScoreData.value[quotaId][index] === undefined) {
          resultScoreData.value[quotaId][index] = 0;
        }
      });
    }
  });
};

// 计算结果页面时间分段
const calculateResultTimeSegments = (
  planDuration: number,
  segmentTime: number
) => {
  const segments: Array<{ label: string; duration: number }> = [];
  let currentTime = 0;

  while (currentTime < planDuration) {
    const remainingTime = planDuration - currentTime;

    // 如果剩余时间不足一个完整分段，且已经有分段存在，则合并到最后一个分段
    if (remainingTime < segmentTime && segments.length > 0) {
      // 将剩余时间合并到最后一个分段，累计时间为总时长
      segments[segments.length - 1].duration = planDuration;
      segments[segments.length - 1].label = `${(planDuration / 60).toFixed(
        0
      )}分钟得分`;
      break;
    }

    const nextTime = currentTime + segmentTime;
    segments.push({
      label: `${(nextTime / 60).toFixed(0)}分钟得分`,
      duration: nextTime,
    });

    currentTime = nextTime;
  }
  resultTimeSegments.value = segments;
};

// 解析并填充结果页面已有的评价结果
const parseAndFillResultExistingResults = (
  results: EvaluateTaskResultType[]
) => {
  results.forEach((result) => {
    if (result.quotaId && result.segmentScore) {
      try {
        // 解析 segmentScore 格式 "{1:7,2:8}"
        const segmentScores = JSON.parse(
          result.segmentScore.replace(/(\w+):/g, '"$1":')
        );

        // 将分数填入 scoreData
        if (!resultScoreData.value[result.quotaId]) {
          resultScoreData.value[result.quotaId] = {};
        }

        Object.keys(segmentScores).forEach((segmentIndex) => {
          const index = parseInt(segmentIndex) - 1; // 转换为从0开始的索引
          if (index >= 0 && index < resultTimeSegments.value.length) {
            resultScoreData.value[result.quotaId][index] =
              segmentScores[segmentIndex];
          }
        });
      } catch (error) {
        console.error("解析分段分数失败：", error);
      }
    }
  });
};

// 关闭结果弹框
function handleResultClose() {
  dialogResultVisible.value = false;
  currentResultTask.value = null;
  currentResourcePreviewUrl.value = "";
  resultCurrentTab.value = "";
  resultCurrentTabDataMap.value = {};
  resultScoreData.value = {};
  resultQuotaList.value = [];
  resultTableQuotaList.value = [];
  resultTimeSegments.value = [];
}
</script>

<style scoped lang="scss">
#RecordBackPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 2rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 3px;
  height: 1.8rem;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  background-color: #fff;
  flex-shrink: 0;
  padding: 1.5rem 0;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    padding: 2rem 2rem 0 2rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    margin-bottom: 1rem;
    .item-label {
      display: inline;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: right;
      color: $text-color-regular;
      min-width: 5rem;
    }
    .item-input {
      width: 20rem;
    }
    // 专门为多选下拉框和日期选择器设置更大的宽度
    .item-input:is(.el-select, .el-date-editor) {
      // width: 24rem;
    }
  }
  .search-btn {
    display: flex;
    align-items: center;
    height: 3rem;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem 0;
  background-color: #fff;
  .table-wrapper {
    padding: 0 2rem;
    flex: 1;
    min-height: 0;
    margin-top: 1.5rem;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .signal-status.normal {
    color: $color_success;
  }
  .signal-status.abnormal {
    color: $color_danger;
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}

// 设置宽高16:9
:deep(.el-dialog) {
  margin-top: 3rem !important;
}

// 弹框样式
:deep(.template-dialog) {
  height: 90vh;
  position: relative;
  .template-form {
    display: flex;
    align-items: start;
    .template-form-item {
      margin-right: 8rem;
    }
    .label {
      width: 7rem !important;
      font-size: $font-size-base;
      color: $text-color-primary;
    }
    .value {
      flex: 1;
      margin-left: 1rem;
      font-size: $font-size-base;
      color: $text-color-regular;
      border: 1px solid $border-color-primary;
      border-radius: 0.5rem;
      padding: 0.5rem 1rem;
    }
  }

  .quota-section {
    margin-top: 2rem;
    height: calc(90vh - 15rem);
  }

  .el-table {
    height: calc(100%);
    .el-table__cell {
      vertical-align: top !important;
    }
  }
}

// 查看结果弹框样式
:deep(.result-dialog) {
  position: relative;
  .result-content {
    display: flex;
    flex-direction: column;
  }

  .task-info {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 2rem;
    padding: 1rem 2rem;
    background-color: #f5f7fa;
    border-radius: 0.5rem;

    .info-item {
      display: flex;
      align-items: center;
      margin-right: 5%;
      .label {
        font-size: $font-size-base;
        color: $text-color-primary;
        font-weight: 500;
      }
      .value {
        font-size: $font-size-base;
        color: $text-color-regular;
      }
    }
  }

  .main-content {
    display: flex;
    gap: 2rem;
  }

  .left-section {
    width: 40%;
    height: 50vh;

    .preview-wrapper {
      height: 100%;
      border: 1px solid $border-color-primary;
      border-radius: 0.5rem;
      overflow: hidden;
    }
  }

  .right-section {
    display: flex;
    flex-direction: column;
    width: 60%;
    height: 50vh;
    .tabs-wrapper {
      display: inline-flex;
      flex-direction: row;
      justify-content: flex-start;
      border: 1px solid $color_brand;
      border-radius: 0.5rem;
      margin-bottom: 1rem;

      .tab-item {
        display: inline-flex;
        padding: 0.5rem 1rem;
        background-color: #fff;
        font-size: $font-size-base;
        color: $text-color-regular;
        border-right: 1px solid $border-color-brand;
        cursor: pointer;
        white-space: nowrap;

        &:last-child {
          border-right: none;
        }
        &:hover {
          background-color: $color_brand;
          color: #fff;
        }
        &.active {
          background-color: $color_brand;
          color: #fff;
        }
      }
    }

    .result-table {
      flex: 1;
      min-height: 0;

      .el-table {
        height: 100%;

        .average-score {
          font-size: $font-size-base;
          color: $text-color-regular;
        }

        .total-score {
          font-size: $font-size-base;
          color: $color_brand;
          font-weight: 500;
        }

        .score-cell {
          font-size: $font-size-base;
          color: $text-color-regular;
        }
      }
    }
  }
}
</style>
